package vn.co.thn.android.videohot.activity;

import java.util.ArrayList;
import java.util.Collections;

import vn.co.thn.android.serviceconnect.callback.RequestCallBack;
import vn.co.thn.android.serviceconnect.request.Param;
import vn.co.thn.android.videohot.R;
import vn.co.thn.android.videohot.VHApp;
import vn.co.thn.android.videohot.VHConstants;
import vn.co.thn.android.videohot.VHUrlApi;
import vn.co.thn.android.videohot.adapter.VHCategorySpinnerAdapter;
import vn.co.thn.android.videohot.common.VHCommonActivity;
import vn.co.thn.android.videohot.data.VHCategoryItemData;
import vn.co.thn.android.videohot.data.VHListUploadItemData;
import vn.co.thn.android.videohot.data.VHResultUpload;
import vn.co.thn.android.videohot.data.VHUploadItemData;
import vn.co.thn.android.videohot.task.VHAuthTask;
import vn.co.thn.android.videohot.task.VHAuthTask.AuthCallBack;
import vn.co.thn.android.videohot.task.VHUploadTask;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTubeScopes;
import com.google.api.services.youtube.model.Video;

import vn.co.thn.android.videohot.task.VHUploadTask.UploadCallBack;

public class VHUpLoadVideoActivity extends VHCommonActivity implements OnItemSelectedListener, UploadCallBack, AuthCallBack {
	public Uri videoUri = null;
	private String mEmail;
	public YouTube youtube;
	final HttpTransport transport = AndroidHttp.newCompatibleTransport();
	final JsonFactory jsonFactory = new GsonFactory();
	GoogleAccountCredential credential;
	public ProgressDialog dialog = null;
	private Spinner sp_category;
	EditText et_title, et_description;
	VHCategoryItemData category_choose = new VHCategoryItemData();
	String mFilePath;
	long filesize;
	private InterstitialAd mInterstitial;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vh_upload_video_activity);
		videoUri = getIntent().getData();
		mEmail = VHApp.getPreference().getEmailAccount(null);
		credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(YouTubeScopes.YOUTUBE_UPLOAD));
		if (mEmail == null) {
			Auth();
		} else {
			credential.setSelectedAccountName(mEmail);
			youtube = new com.google.api.services.youtube.YouTube.Builder(transport, jsonFactory, credential).setApplicationName("videohot/1.5").build();
			new VHAuthTask(this, this).execute(mEmail);
		}
		findViewById(R.id.btn_upload).setOnClickListener(this);
		findViewById(R.id.btn_auth).setOnClickListener(this);
		sp_category = (Spinner) findViewById(R.id.sp_category);
		sp_category.setAdapter(new VHCategorySpinnerAdapter(this, VHApp.getPreference().getCategoryList().getCategory_list()));
		sp_category.setOnItemSelectedListener(this);
		@SuppressWarnings("deprecation")
		Cursor cursor = managedQuery(this.videoUri, null, null, null, null);
		if (cursor.getCount() == 0) {
			Toast.makeText(VHUpLoadVideoActivity.this, "not a valid video uri", Toast.LENGTH_LONG).show();
		} else {
			if (cursor.moveToFirst()) {
				long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.VideoColumns._ID));
				ImageView thumbnail = (ImageView) findViewById(R.id.thumbnail);
				ContentResolver crThumb = getContentResolver();
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 2;
				try {
					mFilePath = cursor.getString(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DATA));
					filesize = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.VideoColumns.SIZE));
					Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, id, MediaStore.Video.Thumbnails.MINI_KIND, options);
					if (curThumb.getWidth() > 0)
						thumbnail.setImageBitmap(curThumb);
				} catch (Exception e) {
					thumbnail.setVisibility(View.GONE);
				}
			}
		}
		et_title = (EditText) findViewById(R.id.et_title);
		et_description = (EditText) findViewById(R.id.et_description);
		dialog = new ProgressDialog(this);
		dialog.setTitle(getString(R.string.text_upload));
		dialog.setMessage(getString(R.string.text_msg_upload));
		dialog.setMax(100);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		// ad
				mInterstitial = new InterstitialAd(this);
				mInterstitial.setAdUnitId(getResources().getString(R.string.admod_id));
				mInterstitial.setAdListener(new AdListener() {
					@Override
					public void onAdOpened() {
						// TODO Auto-generated method stub
						super.onAdOpened();
						
					}

					@Override
					public void onAdLoaded() {
						// TODO Auto-generated method stub
						super.onAdLoaded();
						if (mInterstitial.isLoaded()) {
							mInterstitial.show();
						} else {
							mInterstitial.show();
						}
					}
				});
				mInterstitial.loadAd(new AdRequest.Builder().build());

	}

	private boolean isDeviceOnline() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		}
		return false;
	}

	protected void Auth() {
		mEmail = VHApp.getPreference().getEmailAccount(null);
		int statusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
		if (statusCode == ConnectionResult.SUCCESS) {
			if (mEmail == null) {
				pickUserAccount();
			} else {
				if (isDeviceOnline()) {
					// start upload
					credential.setSelectedAccountName(mEmail);
					youtube = new com.google.api.services.youtube.YouTube.Builder(transport, jsonFactory, credential).setApplicationName("videohot/1.5")
							.build();
					new VHAuthTask(this, this).execute(mEmail);
				} else {
					Toast.makeText(this, "No network connection available", Toast.LENGTH_SHORT).show();
				}
			}

		} else if (GooglePlayServicesUtil.isUserRecoverableError(statusCode)) {
			Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode, this, 0);
			dialog.show();
		} else {
		}
	}

	private void pickUserAccount() {
		startActivityForResult(credential.newChooseAccountIntent(), VHConstants.REQUEST_CODE_PICK_ACCOUNT);
	}

	private void handleAuthorizeResult(int resultCode, Intent data) {
		if (data == null) {
			return;
		}
		if (resultCode == RESULT_OK) {
			Auth();
			return;
		}
		if (resultCode == RESULT_CANCELED) {
			Toast.makeText(this, " User rejected authorization.", Toast.LENGTH_SHORT).show();
			findViewById(R.id.btn_auth).setVisibility(View.VISIBLE);
			showAuth(true);
			showUpload(false);
			showError("User rejected authorization.");
			return;
		}
		// show("Unknown error, click the button again");
		Toast.makeText(this, " Unknown error, click the button again", Toast.LENGTH_SHORT).show();
	}

	public void handleException(final Exception e) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (e instanceof GooglePlayServicesAvailabilityException) {
					int statusCode = ((GooglePlayServicesAvailabilityException) e).getConnectionStatusCode();
					Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode, VHUpLoadVideoActivity.this,
							VHConstants.REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
					dialog.show();
				} else if (e instanceof UserRecoverableAuthException) {
					Intent intent = ((UserRecoverableAuthException) e).getIntent();
					startActivityForResult(intent, VHConstants.REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VHConstants.REQUEST_CODE_PICK_ACCOUNT) {
			if (resultCode == RESULT_OK) {
				mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				VHApp.getPreference().setEmailAccount(mEmail);

				// upload
				Auth();
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "You must pick an account", Toast.LENGTH_SHORT).show();
				showUpload(false);
				showAuth(true);
				showError("You must pick an account");
			} else if ((requestCode == VHConstants.REQUEST_CODE_RECOVER_FROM_AUTH_ERROR || requestCode == VHConstants.REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
					&& resultCode == RESULT_OK) {
				handleAuthorizeResult(resultCode, data);
				return;
			}
		} else if ((requestCode == VHConstants.REQUEST_CODE_RECOVER_FROM_AUTH_ERROR || requestCode == VHConstants.REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)) {
			handleAuthorizeResult(resultCode, data);
			return;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.btn_upload:
			String[] data = new String[3];
			data[0] = et_title.getText().toString().trim();
			data[1] = et_description.getText().toString().trim();

			if (TextUtils.isEmpty(data[0])) {
				showError(getString(R.string.txt_input_title));
				return;
			}
			if (TextUtils.isEmpty(data[1])) {
				showError(getString(R.string.txt_input_category));
				return;
			}
			if (category_choose == null) {
				showError(getString(R.string.txt_input_decripton));
				return;
			}
			data[2] = category_choose.getKey() + "";
			// new
			new VHUploadTask(youtube, mFilePath, this).execute(data);
			break;
		case R.id.btn_auth:
			Auth();
			break;
		default:
			break;
		}
	}

	public void showUpload(boolean isShow) {
		if (isShow) {
			findViewById(R.id.btn_upload).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.btn_upload).setVisibility(View.GONE);
		}
	}

	public void showAuth(boolean isShow) {
		if (isShow) {
			findViewById(R.id.btn_auth).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.btn_auth).setVisibility(View.GONE);
		}
	}

	public void showError(String sms) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setMessage(sms).setTitle("Error");

		AlertDialog dialog = builder.create();
		dialog.show();
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		if (position != 0) {
			category_choose = (VHCategoryItemData) parent.getItemAtPosition(position);
		} else {
			category_choose = null;
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub

	}

	@Override
	public void start() {
		// TODO Auto-generated method stub
		this.dialog.show();
	}

	@Override
	public void inProcess(Integer update_process) {
		// TODO Auto-generated method stub

	}

	@Override
	public void conplete(Video video) {
		if (video != null) {
			VHUploadItemData obj = new VHUploadItemData();
			obj.setDeviceId(VHApp.getDeviceID());
			obj.setPath(this.mFilePath);
			obj.setFileSize(this.filesize + "");
			VHListUploadItemData Upload_list = new VHListUploadItemData();
			if (VHApp.getPreference().getUploadList() != null) {
				Upload_list = VHApp.getPreference().getUploadList();
				Upload_list.getHistory_upload_list().add(obj);
				VHApp.getPreference().setUploadList(Upload_list);
			} else {
				Upload_list.getHistory_upload_list().add(obj);
				VHApp.getPreference().setUploadList(Upload_list);
			}
			this.mRequestService.setUrl(VHUrlApi.Api_UploadHistory_add);
			ArrayList<Param> params = new ArrayList<Param>();
			params.add(new Param("DeviceId", VHApp.getDeviceID()));
			params.add(new Param("PathFile", this.mFilePath));
			params.add(new Param("FileSize", this.filesize + ""));
			params.add(new Param("embed_code", video.getId()));
			params.add(new Param("title", et_title.getText().toString().trim()));
			params.add(new Param("content", et_description.getText().toString().trim()));
			params.add(new Param("category_key", category_choose.getKey()));
			params.add(new Param("email", mEmail));
			this.mRequestService.setParams(params);
			this.mRequestService.setRequestCallBack(new RequestCallBack<VHResultUpload>() {

				@Override
				public void onResult(VHResultUpload data, boolean isUpdate) {
					// TODO Auto-generated method stub
					if (VHApp.getPreference().getDeviceID() == null) {
						VHApp.getPreference().setDeviceID(data.getUploadHistory().getDeviceId());
					}

					if (data.getError_code() == 1) {
						showError(getString(R.string.txt_exits_file));
					}
					dialog.dismiss();
					finish();
				}

				@Override
				public void onResult(ArrayList<VHResultUpload> data, boolean isUpdate) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					finish();
				}

			});
			this.mRequestService.Post();
		} else {
			dialog.dismiss();
		}
	}

	@Override
	public void AuthSuccess() {
		// TODO Auto-generated method stub
		showUpload(true);
		showAuth(false);
		VHListUploadItemData Upload_list = VHApp.getPreference().getUploadList();
		if (Upload_list != null) {
			if (Upload_list.getHistory_upload_list().size() > 0) {
				ArrayList<VHUploadItemData> lst_upload = Upload_list.getHistory_upload_list();
				VHUploadItemData obj = new VHUploadItemData();
				obj.setDeviceId(VHApp.getDeviceID());
				obj.setPath(this.mFilePath);
				obj.setFileSize(this.filesize + "");

				for (VHUploadItemData objs : lst_upload) {
					if (objs.getDeviceId().equalsIgnoreCase(obj.getDeviceId()) && objs.getPath().equalsIgnoreCase(obj.getPath())
							&& objs.getFileSize().equalsIgnoreCase(obj.getFileSize())) {
						showError(getString(R.string.txt_exits_file));
						showUpload(false);
						return;
					}
				}
			}
		}
	}

	@Override
	public void AuthError(Exception e) {
		// TODO Auto-generated method stub
		showUpload(false);
		showAuth(true);
		if (e instanceof UserRecoverableAuthException) {
			handleException(e);
		} else {
			VHApp.getPreference().setEmailAccount(null);
		}
	}
}
